#!/usr/bin/python
#

simulator = False
backlight_is_on = False

if simulator: 
    import simulator as lcd
    import simulator as buttons
else:
    import hd44780 as lcd
    import keypad as buttons

import gui

backlight_sec_tick = 0

import time
import threading
class BacklightTimer(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
    def run (self):
        global backlight_sec_tick
	backlight_sec_tick = 0
        while True:
            if backlight_sec_tick > 120:
                lcd.backlight_off()
		backlight_sec_tick = 0
            time.sleep(1.0)
	    if lcd.backlight_is_on == True:
                backlight_sec_tick = backlight_sec_tick + 1

def on_keypress(key, char):
    global backlight_sec_tick
    backlight_sec_tick = 0
    if not lcd.is_backlight_on():
        lcd.backlight_on()
        return
    if key == 'b':
        lcd.backlight_off()
    if key == 'Left':   
        gui.left()
#    if key == 'Middle':
#	lcd.backlight_off() if lcd.is_backlight_on() else lcd.backlight_on()
    if key == 'Right' or key == 'Middle':
        gui.right()
    if key == 'Up':
        gui.up()
    if key == 'Down': 
        gui.down()
 
def print_line(line, string):
    lcd.display(line, string)
       
def main():

  # Initialise display
  if not simulator:
      lcd.gpio_init()
      lcd.lcd_init()
  bl_timer = BacklightTimer()
  bl_timer.setDaemon(True)
  bl_timer.start()
  lcd.clear()
  gui.init(print_line)
  gui.right()
  buttons.wait_for_keypress(on_keypress)

if __name__ == '__main__':
  main()
